package com.wtf.dsp.admin.core.support;

import com.baomidou.mybatisplus.annotation.DbType;
import com.wtf.dsp.admin.config.CustomMybatisConfiguration;
import com.wtf.dsp.admin.core.parser.MapperXmlResourceParser;
import com.wtf.dsp.admin.core.parser.ParamNameResolver;
import com.wtf.dsp.admin.core.table.DbTableSql;
import com.wtf.dsp.admin.enums.CommonErrorEnum;
import com.wtf.dsp.admin.exception.WtfDspException;
import com.wtf.dsp.admin.util.SqlInterceptor;
import com.wtf.dsp.core.enums.TableApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.springframework.beans.factory.InitializingBean;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: DbSqlMapperRepositorySupport
 * Description:
 * date: 2024/9/5 11:17
 *
 * @author linhuanyou
 * @version 1.0
 */
@Slf4j
public class DbSqlMapperRepositorySupport  implements DbTableSql , InitializingBean {

    private volatile CustomMybatisConfiguration cutomMybatisConfiguration = new CustomMybatisConfiguration();

    private String resource = "db/Db.xml";
    private static String DB_TYPE_PARAMS = "dbType";

    public void afterPropertiesSet() throws Exception {
        InputStream resourceAsStream = null;
        try {
            resourceAsStream = Resources.getResourceAsStream(resource);
            MapperXmlResourceParser.loadMapperResource(resource,resourceAsStream,cutomMybatisConfiguration);
        } catch (IOException e) {
            log.error("Loading Db Table Sql Error : {}",e.getMessage());
            throw new RuntimeException(e);
        }
    }

    @Override
    public String tableSql(DbType dbType, TableApi tableApi,Map<String,Object> params) {
        MappedStatement mappedStatement = cutomMybatisConfiguration.getMappedStatement(tableApi.toString().toLowerCase());
        if(mappedStatement == null){
            throw new WtfDspException(CommonErrorEnum.MAPPER_SQL_NOT_EXIST);
        }
        params.put(DB_TYPE_PARAMS, dbType.getDb());
        BoundSql boundSql = mappedStatement.getBoundSql(ParamNameResolver.getNamedParams(params));
        return SqlInterceptor.formatSql(cutomMybatisConfiguration, boundSql);
    }
}
